package com.esir.android.base;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.esir.android.R;

/**
 * 承载显示Fragment
 */
public final class FragmentActivity extends BaseActivity {
    /**
     * 当前显示，获取售点的Fragment片
     **/
    Fragment currentFragment;
    /**
     * 结合路由完成
     */
    public final static String P_OPTION_FRAGMENT_PATH = "fragment_uri";
    public final static String P_SOFT_INPUT_MODEL = "softInputModel";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Bundle args = getIntent().getExtras();
        super.onCreate(savedInstanceState);

        FrameLayout fragmentContainer = new FrameLayout(this);
        fragmentContainer.setLayoutParams(new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
        fragmentContainer.setId(R.id.content_container);
        setContentView(fragmentContainer);

        Fragment fragment = initFragment();
        if (fragment != null) {
            //直接把参数传递过去
            fragment.setArguments(args);
            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction transaction = fragmentManager.beginTransaction();   // 开启一个事务
            transaction.replace(R.id.content_container, fragment);
            transaction.commit();
        }
    }

    private Fragment initFragment() {
        String uri = getIntent().getStringExtra(P_OPTION_FRAGMENT_PATH);

        if (!TextUtils.isEmpty(uri)) {
            //通过路由工具获取实例
//            currentFragment = ARouterUtils.getFragment(uri);

            //尝试反射实例化
            if (currentFragment == null) {
                try {
                    currentFragment = (Fragment) Class.forName(uri).newInstance();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                }
            }
        }

        return currentFragment;
    }

    @Override
    protected void initView() {

    }
}
